package com.ruoyi.service.impl;

import com.ruoyi.domain.Comment;
import com.ruoyi.domain.CommentDTO;
import com.ruoyi.domain.CommentVo;
import com.ruoyi.mapper.CommentMapper;
import com.ruoyi.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private com.ruoyi.writer.mapper.ChapterMapper chapterMapper;
    @Override
    public int addComment(Comment comment) {
        String userName = chapterMapper.selectAuthorNameByUserId(comment.getUserId());
        String userAvatar = commentMapper.getUserAvatar(comment.getUserId());
        Long novelId = chapterMapper.selectNovelId(comment.getTitle());
        comment.setNovelId(novelId);
        comment.setUserName(userName);
        comment.setAvatar(userAvatar);
        return commentMapper.addComment(comment);
    }

    @Override
    public List<CommentDTO>  getCommentList(String title) {
        // 1. 获取小说ID
        Long novelId = chapterMapper.selectNovelId(title);

        // 2. 查询所有评论（平铺结构）
        List<CommentDTO> allComments = commentMapper.selectCommentList(novelId);

        // 3. 组装树形结构
        Map<Long, CommentDTO> commentMap = new HashMap<>();
        List<CommentDTO> topLevelComments = new ArrayList<>();

        // 第一遍遍历：识别所有评论（包括顶级和非顶级）
        for (CommentDTO comment : allComments) {
            commentMap.put(comment.getId(), comment);

            // 明确判断 parent_id 是否为 null
            if (comment.getParentId() == 0) {
                topLevelComments.add(comment);
            }
        }

        // 第二遍遍历：挂载子评论
        for (CommentDTO comment : allComments) {
            if (comment.getParentId() != 0) {
                CommentDTO parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    parent.getReplies().add(comment);
                }
            }
        }

        return topLevelComments;
    }

    @Override
    public int deleteComment(Long CommentID) {
        int result = commentMapper.deleteComment(CommentID);
        return result;
    }

    @Override
    public String getUserAvatar(Long userId) {
        return commentMapper.getUserAvatar(userId);
    }
}
